<script setup lang="ts">
import { useProjectStore } from '@/store/project';
import { useUserStore } from '@/store/user';
import { IProjectInfoProps } from '@/types/projectType';
import { onMounted, ref } from 'vue';

defineProps({
  show: {
    type: Boolean,
    default: false,
  }
})

const emit = defineEmits([
  'confirm',
  'setShow',
  'setDefaultValue'
]);

const userStore = useUserStore();
const projectStore = useProjectStore();

const columns = [
  { name: '东莞金町湾11', id: 1 },
  { name: '惠州茉莉花园1', id: 2 },
  { name: '广州林语花园1', id: 3 },
  { name: '东莞金町湾2', id: 4 },
  { name: '惠州茉莉花园2', id: 5 },
  { name: '广州林语花园2', id: 6 },
  { name: '东莞金町湾3', id: 7 },
  { name: '惠州茉莉花园3', id: 8 },
  { name: '广州林语花园3', id: 9 },
]
const projectColumns = ref<IProjectInfoProps[]>(projectStore.projectList?.length ? projectStore.projectList as IProjectInfoProps[] : columns);
projectStore.setProjectList(projectColumns.value);
const searchValue = ref('');
console.log('props.columns', projectColumns.value[0]);
const currentItem = ref<IProjectInfoProps>(projectColumns.value[0] as IProjectInfoProps);

const searchHandler = () => {
  const temp = columns.filter((item) => {
    return item.name.includes(searchValue.value);
  });
  projectColumns.value = temp;
}

const clearHandler = () => {
  projectColumns.value = columns;
}

const changHandler = (e:string) => {
  if (!e) {
    projectColumns.value = columns;
  }
}

const cancelHandler = () => {
  emit('setShow', false)
  searchValue.value = ''
}

const pickerConfirmHandler = (target: any) => {
  if (!target.value[0]) {
    uni.$u.toast('请选择项目');
    return
  }
  const item = target.value[0];
  console.log('pickerConfirmHandler', target);
  currentItem.value = {
    name: item.name,
    id: item.id,
  }
  emit('confirm', item)
  emit('setShow', false)
  searchValue.value = ''
}

onMounted(() => {
  console.log('onMounted', projectColumns.value[0])
  emit('setDefaultValue', projectColumns.value[0])
})
</script>

<template>
  <up-picker
    :show="show" 
    :columns="[projectColumns]" 
    keyName="name"
    :showToolbar="true"
    confirmColor="#d54448"
    @cancel="cancelHandler"
    @confirm="pickerConfirmHandler"
  >
    <template #toolbar-bottom>
      <view class="project-search-input-box">
        <up-search
          :show-action="true"
          actionText="搜索"
          :animation="true"
          :clearabled="true"
          v-model="searchValue"
          @search="searchHandler"
          @custom="searchHandler"
          @clear="clearHandler"
          @change="changHandler"
        ></up-search>
      </view>
    </template>
  </up-picker>
</template>

<style lang="scss" scoped>
.project-search-input-box {
  padding: 16rpx 30rpx;
}
</style>